package com.ruicar.afs.cloud.product.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.product.condition.DiscountRulePlanCondition;
import com.ruicar.afs.cloud.product.entity.ProductDiscountRule;
import com.ruicar.afs.cloud.product.entity.SchemeFinance;
import com.ruicar.afs.cloud.product.enums.FitScope;
import com.ruicar.afs.cloud.product.enums.StatusEnum;
import com.ruicar.afs.cloud.product.enums.StatusType;
import com.ruicar.afs.cloud.product.service.ProductDiscountRulePlanService;
import com.ruicar.afs.cloud.product.service.ProductRuleInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * @author xudongdong
 * @date 2020-05-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/discountRulePlan")
@Api(value = "productDiscountPlan", description = "产品贴息方案")
public class ProductDiscountRulePlanController {

    private final ProductDiscountRulePlanService productDiscountRulePlanService;
    private final ProductRuleInfoService ruleInfoService;
    private final AfsSequenceGenerator afsSequenceGenerator;

    @PostMapping(value = "/getDiscountRulePlanList")
    @ApiOperation(value = "多条件分页获取贴息规则方案")
    public IResponse<IPage<ProductDiscountRule>> listProductDiscountPlan(@RequestBody QueryCondition<DiscountRulePlanCondition> rulePlan) {
        return IResponse.success(productDiscountRulePlanService.page(new Page(rulePlan.getPageNumber(), rulePlan.getPageSize()), Wrappers.<ProductDiscountRule>query().lambda()
                .like(StringUtils.isNotEmpty(rulePlan.getCondition().getName()), ProductDiscountRule::getName, rulePlan.getCondition().getName())
                .eq(StringUtils.isNotEmpty(rulePlan.getCondition().getStatus()), ProductDiscountRule::getStatus, rulePlan.getCondition().getStatus())
                .like(StringUtils.isNotEmpty(rulePlan.getCondition().getPlanNo()), ProductDiscountRule::getPlanNo, rulePlan.getCondition().getPlanNo())
                .orderByDesc(ProductDiscountRule::getCreateTime)
        ));
    }

    @RequestMapping(value = "/saveDiscountRulePlan", method = RequestMethod.POST)
    @ApiOperation(value = "贴息规则方案保存")
    public IResponse<SchemeFinance> saveFinancePlan(@RequestBody ProductDiscountRule productDiscountRule) {
        //查询是否有相同编号的方案
        ProductDiscountRule productDiscountRule1 = productDiscountRulePlanService.getOne(Wrappers.<ProductDiscountRule>query().lambda()
                        .eq(ProductDiscountRule::getName, productDiscountRule.getName())
                , false
        );
        if (productDiscountRule1 != null && productDiscountRule.getId() == null) {
            return IResponse.fail("名称重复，请重新填写方案名称！");
        }
        //获取编号
        String planNo = productDiscountRule.getPlanNo();
        if(StringUtils.isEmpty(planNo)){
            Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_BTGZ), StatusType.PRODUCT_NUM_BTGZ.toString());
            planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_BTGZ) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
            productDiscountRule.setPlanNo(planNo);
        }
        productDiscountRulePlanService.saveOrUpdate(productDiscountRule);
        return IResponse.success(productDiscountRule);
    }

    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "通过id删除贴息规则方案")
    public IResponse<Boolean> deletePlan(@PathVariable String id) {
        ProductDiscountRule productDiscountRule = productDiscountRulePlanService.getById(id);
        if (AfsEnumUtil.key(StatusEnum.YES).equals(productDiscountRule.getStatus())) {
            return new IResponse<Boolean>().setMsg("生效方案不可删除！");
        } else {
            /**
             * 第一步：删除产品规则信息
             */
            ruleInfoService.delProductRuleInfoList(productDiscountRule.getId(), AfsEnumUtil.key(FitScope.DISCOUNTSUBSIDY));
            /**
             * 第二步：删除方案
             */
            productDiscountRulePlanService.removeById(id);
            return new IResponse<Boolean>().setMsg("删除数据成功!");
        }
    }

    @RequestMapping(value = "/effective", method = RequestMethod.POST)
    @ApiOperation(value = "设置有效")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> effective(@ModelAttribute DiscountRulePlanCondition plancondition) {
        for (Long id : plancondition.getIds()) {
            ProductDiscountRule plan = productDiscountRulePlanService.getById(id);
            plan.setStatus(AfsEnumUtil.key(StatusEnum.YES));
            productDiscountRulePlanService.updateById(plan);
            ruleInfoService.effectiveRule(plan.getId(), AfsEnumUtil.key(FitScope.DISCOUNTSUBSIDY),plan.getName());
        }
        return new IResponse<Boolean>().setData(true).setMsg("批量设置数据有效成功");
    }

    @RequestMapping(value = "/invalid", method = RequestMethod.POST)
    @ApiOperation(value = "设置无效")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> invalid(@ModelAttribute DiscountRulePlanCondition plancondition) {
        for (Long id : plancondition.getIds()) {
            ProductDiscountRule plan = productDiscountRulePlanService.getById(id);
            plan.setStatus(AfsEnumUtil.key(StatusEnum.NO));
            productDiscountRulePlanService.updateById(plan);
            ruleInfoService.invalid(plan.getId(), AfsEnumUtil.key(FitScope.DISCOUNTSUBSIDY));
        }
        return new IResponse<Boolean>().setData(true).setMsg("批量设置数据无效成功");
    }

    @RequestMapping(value = "/copyPlan", method = RequestMethod.POST)
    @ApiOperation(value = "产品投放方案复制")
    public IResponse copyPlan(@RequestBody ProductDiscountRule plan) {
        //查询是否有相同编号的方案
        ProductDiscountRule scheme = productDiscountRulePlanService.getOne(Wrappers.<ProductDiscountRule>query().lambda()
                        .eq(ProductDiscountRule::getName, plan.getName())
                , false
        );
        if (scheme != null) {
            return IResponse.fail("名称重复，请重新填写方案名称！");
        }
        //获取编号
        Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_BTGZ), StatusType.PRODUCT_NUM_BTGZ.toString());
        String planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_BTGZ) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
        plan.setPlanNo(planNo);
        //原方案ID
        Long schemeLaunchOldId = plan.getId();
        //保存方案
        plan.setId(null);
        plan.setStatus(AfsEnumUtil.key(StatusType.INVALID));
        plan.setCreateBy(null);
        plan.setCreateTime(null);
        productDiscountRulePlanService.save(plan);
        //新方案ID
        String schemeLaunchNewId = plan.getId().toString();
        //复制规则信息
        ruleInfoService.copyRulePlan(schemeLaunchOldId, schemeLaunchNewId, AfsEnumUtil.key(FitScope.DISCOUNTSUBSIDY));
        return IResponse.success(plan);
    }
}
